package org.bbelovic.devel.snake;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class CircleGenerator {

    private static final int DEFAULT_COUNTDOWN = 30;
    private static final int CIRCLE_SIZE = Snake.getSnakesCircleSize();
    private static final Random RANDOM = new Random();
    private final int xCoordinateBound;
    private final int yCoordinateBound;
    /** stores coordinates for circle which have to be caught by a snake */
    private int [] circleCoordinates;
    /** signals whether new circle has been caught by a snake */
    private boolean circleCaught;
    private boolean newCoordinatesNeeded = true;
    /** if equal to zero, new circle is displayed */
    private int countDown = DEFAULT_COUNTDOWN;

    /**
     * Constructs new instance.
     * @param width max value of x-coordinate for newly created circle
     * @param height max value of y-coordinate for newly created circle
     */
    public CircleGenerator(final int width, final int height) {
        this.xCoordinateBound = width - 2 * CIRCLE_SIZE;
        this.yCoordinateBound = height - 2 * CIRCLE_SIZE;
        this.circleCoordinates = new int [2];
    }

    public void countDown() {
        if (circleCaught && countDown-- == 0) {
            circleCaught = false;
            countDown = DEFAULT_COUNTDOWN;
        }
    }

    public void drawCircle(final Graphics g) {
        if (newCoordinatesNeeded) {
            generateNewCoordinates();
        }
        if (!circleCaught) {
            Circle circle = new Circle(Color.RED, CIRCLE_SIZE, circleCoordinates [0], circleCoordinates [1]);
            circle.paint(g);
        }
    }

    public void circleCaught() {
        this.circleCaught = true;
        this.newCoordinatesNeeded = true;
    }

    public int getX() {
        return this.circleCoordinates [0];
    }

    public int getY() {
        return this.circleCoordinates [1];
    }

    public boolean isCircleCaught() {
        return this.circleCaught;
    }
    
    public int getCountDown() {
        return this.countDown;
    }

    private void generateNewCoordinates() {
        final int x = RANDOM.nextInt(xCoordinateBound);
        final int y = RANDOM.nextInt(yCoordinateBound);
        int rem = x / CIRCLE_SIZE;
        circleCoordinates [0] = rem * CIRCLE_SIZE;
        rem = y / CIRCLE_SIZE;
        circleCoordinates [1] = rem * CIRCLE_SIZE;

        newCoordinatesNeeded = false;
    }

}
